package com.knife.mybatisplus.extension.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author qiang.zhang Date 2022-02-28 22:52
 * 描述：
 * 作用： 通过 mybatis 提供的自定义类型解析，实现数据 存/取时， List 和 String 之间互相转化
 * 用法： 在 xxxMapper.xml 文件对应的字段配置 typeHandler
 *
 * eg.
 *     resultmap 里的字段映射：
 *     <result column="UPLOAD_ATTACHMENT" jdbcType="VARCHAR" property="uploadAttachment" typeHandler="com.goocidata.supplyx.mes.util.StringListTypeHandler"/>
 *
 *     设置值的时候配置
 *     #{element.uploadAttachment,jdbcType=VARCHAR,typeHandler=com.goocidata.supplyx.mes.util.StringListTypeHandler},
 *
 *
 *
 *     实体类字段上配置：但是依赖 通用 mapper
 *     @ColumnType(jdbcType = JdbcType.VARCHAR,typeHandler = StringListTypeHandler.class)
 *     private List<String> proxyCertificate;
 *
 *
 *
 */
@MappedTypes({List.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class StringListTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        if (strings == null || strings.size() == 0) {
            preparedStatement.setString(i, null);
        } else {
            preparedStatement.setString(i, String.join(",", strings.toArray(new String[strings.size()])));
        }
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String str = resultSet.getString(s);
        if (resultSet.wasNull()) {
            return null;
        }
        return Arrays.asList(str.split(","));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String str = resultSet.getString(i);
        if (resultSet.wasNull()) {
            return null;
        }
        return Arrays.asList(str.split(","));
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String str = callableStatement.getString(i);
        if (callableStatement.wasNull()) {
            return null;
        }
        return Arrays.asList(str.split(","));
    }
}

